<?php

namespace App\Repository;

use App\Models\V1\MemberModel;
use EasyWeChat\Foundation\Application;
use  Carbon\Carbon;
use Illuminate\Support\Facades\Session;



trait WxUserInfoRegister
{
    public function register()
    {

        $comfig   = config('wx');
        $app      = new Application($comfig);
        $user     = $app->oauth->user();

        $wxOpenid = $user->getId();
        $unionId  = $user['original']['unionid'];

        //用户点击评论后查找数据是否已经存在了，如果不存在则在在memberinfo创建数据
        $memberModel= new MemberModel();
        $userInfo = $memberModel->get_member_info_by_unionid($unionId);
        if($userInfo)
        {
            if(empty($userInfo->WeiXID))
            {
                $data   = ['WeiXID'=>$wxOpenid,'UserID'=>$userInfo->UserID];
                $memberModel->update_member_info($data);
                $userInfo->WeiXID = $wxOpenid;
            }
            $userInfo = object_to_array($userInfo);
        }
        else
        {
            $userInfo = WxRegister::create(
                [
                    'WeiXID'      => $wxOpenid,
                    'MemNumber'   => create_member_number(),
                    'NickName'    => $user->getNickname(),
                    'YourName'    => $user->getName(),
                    'FilePath1'   => $user->getAvatar(),
                    'AddDate'     => Carbon::now(),
                    'ReleaseDate' => Carbon::now(),
                    'wx_unionid'  => $user['original']['unionid']
                ]
            );
            $userInfo = $userInfo->toArray();
        }

        Session::put('wxUserInfo', $userInfo);
    }



    //获得微信信息
    public function get_wx_user_info(){
        return Session::get('wxUserInfo');
    }



}